package com.example.demo.leetcode.top100;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _44二叉搜索树中第K小的元素
 * @description
 * @date 2023/06/16 17:56
 * <p>
 * ******************************************************
 */
public class _44二叉搜索树中第K小的元素 {

    int n = -1;
    int target;

    public int kthSmallest(TreeNode root, int k) {
        this.target = k;
        inorderTree(root);
        return n;
    }

    private void inorderTree(TreeNode root) {
        if (root == null) {
            return;
        }
        inorderTree(root.left);
        this.target--;
        if (target == 0) {
            n = root.val;
            return;
        }
        inorderTree(root.right);
    }

    public class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }
}
